package com.cjc.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.cjc.common.utils.R;
import com.cjc.domain.User;
import com.cjc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户控制器
 *
 * @Author: 陈江灿
 * @CreateTime: 2025-01-21
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户信息
     * @param request
     * @return
     */
    @GetMapping("/info")
    public R<User> info(HttpServletRequest request) {
        String token = request.getHeader("sa-token");
        Object id_Obj = StpUtil.getLoginIdByToken(token);
        Long id = Long.valueOf(id_Obj.toString());
        User userById = userService.getUserById(id);
        return R.ok(userById);
    }

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody User user) {
        User login = userService.login(user);
        StpUtil.login(login.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        login.setToken(tokenInfo.getTokenValue());
        return R.ok(login);
    }
}
